
import { 
  ScanTask, 
  TaskType, 
  ScanRecord, 
  ScanStatus, 
  IssueSeverity, 
  ScanIssue, 
  ConfirmationStatus, 
  ConfirmationType,
  ConfirmationHistoryItem
} from '../types';

// --- Task Definitions with Dynamic Field Configs ---

export const TASKS: ScanTask[] = [
  {
    id: 'task-1',
    type: TaskType.HARMONY_API,
    name: 'HarmonyOS Cangjie API Design',
    description: 'Scans for compliance with Cangjie API design guidelines, focusing on naming conventions and signature stability.',
    lastScanTime: '2023-10-26 14:30:00',
    recordFields: [
      { key: 'apiVersion', label: 'API Version', type: 'text' },
      { key: 'moduleScope', label: 'Module Scope', type: 'text' }
    ],
    issueFields: [
      { key: 'apiName', label: 'API Name', type: 'text' },
      { key: 'interfaceType', label: 'Interface Type', type: 'text' },
      { key: 'suggestion', label: 'Fix Suggestion', type: 'code' }
    ]
  },
  {
    id: 'task-2',
    type: TaskType.ARKTS_CONSISTENCY,
    name: 'ArkTS Interface Consistency',
    description: 'Validates consistency between ArkTS interfaces and implementation, checking for type mismatches and missing props.',
    lastScanTime: '2023-10-25 09:15:00',
    recordFields: [
      { key: 'typeCheckLevel', label: 'Type Check Level', type: 'text' }
    ],
    issueFields: [
      { key: 'interfaceName', label: 'Interface', type: 'text' },
      { key: 'mismatchType', label: 'Mismatch Type', type: 'text' }
    ]
  },
  {
    id: 'task-3',
    type: TaskType.CJD_SOURCE,
    name: 'CJD Source Consistency',
    description: 'Ensures CJD source files adhere to project structural rules and dependency constraints.',
    lastScanTime: '2023-10-24 18:00:00',
    recordFields: [
      { key: 'filesScanned', label: 'Files Scanned', type: 'number' }
    ],
    issueFields: [
      { key: 'dependency', label: 'Invalid Dependency', type: 'text' }
    ]
  }
];

// --- Mock Data Generators ---

const generateRecords = (taskId: string, count: number): ScanRecord[] => {
  return Array.from({ length: count }).map((_, i) => ({
    id: `SR-20240401-000${i}`,
    taskId,
    branch: i % 2 === 0 ? 'master' : 'feature/new-ui',
    startTime: new Date(Date.now() - i * 86400000).toISOString(),
    duration: `${Math.floor(Math.random() * 4) + 1}m ${Math.floor(Math.random() * 60)}s`,
    creator: i % 3 === 0 ? 'Alex' : 'Zhang San',
    status: i === 0 ? ScanStatus.COMPLETED : (Math.random() > 0.9 ? ScanStatus.FAILED : ScanStatus.COMPLETED),
    totalIssues: 128 - i * 10,
    confirmedIssues: 40 + i,
    unconfirmedIssues: 88 - i * 11,
    extensionData: {
      apiVersion: 'v2.4.0',
      moduleScope: '/src/api/**',
      filesScanned: 1402,
      typeCheckLevel: 'Strict'
    }
  }));
};

const generateHistory = (isConfirmed: boolean): ConfirmationHistoryItem[] => {
    if (!isConfirmed) return [];
    return [
        {
            id: 'h1',
            timestamp: new Date(Date.now() - 86400000 * 5).toISOString(),
            actor: 'Zhang San',
            type: ConfirmationType.REAL_ISSUE,
            note: 'Confirmed as a real issue, added to backlog.',
            action: 'create'
        },
        {
            id: 'h2',
            timestamp: new Date(Date.now() - 86400000 * 2).toISOString(),
            actor: 'Li Si',
            type: ConfirmationType.FIXED,
            note: 'Fixed in commit ab12c34.',
            action: 'update'
        }
    ]
}

const generateIssues = (recordId: string, taskType: TaskType, count: number): ScanIssue[] => {
  return Array.from({ length: count }).map((_, i) => {
    const isInherited = Math.random() > 0.5;
    const isConfirmed = Math.random() > 0.7;
    
    let extensionData = {};
    if (taskType === TaskType.HARMONY_API) {
      extensionData = { 
          apiName: `get_user_profile_${i}`, 
          interfaceType: 'REST-GET',
          suggestion: 'Unified naming as getUserProfile...' 
      };
    } else if (taskType === TaskType.ARKTS_CONSISTENCY) {
      extensionData = { interfaceName: `IUserProfile`, mismatchType: 'Missing Property' };
    }

    return {
      id: `Q-20240401-${1000 + i}`,
      recordId,
      ruleName: taskType === TaskType.HARMONY_API ? (i % 2 === 0 ? 'API Naming Violation' : 'Signature Mismatch') : 'TypeMismatch',
      severity: i < 2 ? IssueSeverity.CRITICAL : (i < 10 ? IssueSeverity.WARNING : IssueSeverity.INFO),
      filePath: `/src/api/user/profile.ts`,
      lineNumber: 128 + i,
      description: 'API name does not follow camelCase naming convention, suggestion is to use getUserProfile.',
      codeSnippet: `export async function get_user_profile(id: string) {\n  return http.get(\`/api/user/\${id}/profile\`);\n}`,
      confirmationStatus: isConfirmed ? ConfirmationStatus.CONFIRMED : ConfirmationStatus.UNCONFIRMED,
      confirmationType: isConfirmed ? ConfirmationType.FIXED : ConfirmationType.NONE,
      confirmationNote: isConfirmed ? 'Fixed in commit ab12c34' : undefined,
      confirmedBy: isConfirmed ? 'Li Si' : undefined,
      confirmedAt: isConfirmed ? new Date().toISOString() : undefined,
      history: generateHistory(isConfirmed),
      inheritedFromRecordId: isInherited ? `SR-20240301-0012` : undefined,
      extensionData
    };
  });
};

// --- Mock Store ---

export const getTaskById = (id: string) => TASKS.find(t => t.id === id);

export const getRecordsByTask = (taskId: string) => generateRecords(taskId, 5); 

export const getRecordById = (recordId: string) => {
  // Simulate finding a record
  return generateRecords('task-1', 1).map(r => ({...r, id: recordId}))[0];
};

export const getIssuesByRecord = (recordId: string, taskType: TaskType) => generateIssues(recordId, taskType, 15); 

export const triggerScan = async (taskId: string, branch: string): Promise<ScanRecord> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        id: `SR-${Date.now()}`,
        taskId,
        branch,
        startTime: new Date().toISOString(),
        duration: '0s',
        status: ScanStatus.RUNNING,
        totalIssues: 0,
        confirmedIssues: 0,
        unconfirmedIssues: 0,
        creator: 'CurrentUser',
        extensionData: { apiVersion: 'vNext' }
      });
    }, 1000);
  });
};
